<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="租赁名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入租赁名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <treeselect style="width:300px;" v-model="queryParams.categoryId" :options="categoryList" :show-count="true" placeholder="请选择分类" />
      </el-form-item>
       <el-form-item label="运营商" prop="operatorUserId" v-if="getoperatorfunc(this).userType != 1">
        <el-select v-model="queryParams.operatorUserId" placeholder="运营商" filterable clearable style="width: 200px">
          <el-option
            v-for="dict in operatorList"
            :key="dict.id"
            :label="dict.label"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="租赁状态" prop="status" >
        <el-select v-model="queryParams.status" placeholder="租赁状态" filterable clearable style="width: 200px">
          <el-option
            v-for="dict in dict.type.server_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['trade:rentSpu:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="租赁名称" align="center" prop="name"/>
      <el-table-column label="运营商名称" align="center" prop="operatorName" v-if="getoperatorfunc(this).userType != 1"/>
      <el-table-column label="分类名称" align="center" prop="categoryName"/>
      <el-table-column label="租金" align="center" prop="rent"/>
      <el-table-column label="押金" align="center" prop="deposit"/>
      <el-table-column label="虚拟销量" align="center" prop="virtualSalesCount"/>
      <el-table-column label="租赁销量" align="center" prop="salesCount"/>
      <el-table-column label="排序字段" align="center" prop="sort"/>
      <el-table-column label="商品状态" align="center" key="status">
        <template slot-scope="{row}">
          <el-switch v-if="upDateStatusFlag"
          v-model="row.status"
          :active-value="1" :inactive-value="0"
          @change="handleStatusChange(row)"></el-switch>
          <dict-tag :options="dict.type.server_status" v-else :value="row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="text" icon="el-icon-edit" @click="handleUpdate(row)"
            v-hasPermi="['trade:rentSpu:edit']">修改
          </el-button>
          <el-button type="text" icon="el-icon-delete" @click="handleDelete(row)"
            v-hasPermi="['trade:rentSpu:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row >
          <el-col :span="12" >
            <el-form-item label="租赁名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入租赁名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="关键字" prop="keyword">
              <el-input v-model="form.keyword" placeholder="请输入关键字"/>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="分类" prop="categoryId">
              <treeselect v-model="form.categoryId" :options="categoryList" :show-count="true" placeholder="请选择分类" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="运营商" prop="operatorUserId" v-if="getoperatorfunc(this).userType != 1 && !form.id">
              <el-select v-model="form.operatorUserId" placeholder="运营商" filterable clearable style="width: 200px">
                <el-option
                  v-for="dict in operatorList"
                  :key="dict.id"
                  :label="dict.label"
                  :value="Number(dict.id)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="租金" prop="rent">
              <el-input-number v-model="form.rent" :precision="2" :step="1" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="押金" prop="deposit">
              <el-input-number v-model="form.deposit" :precision="2" :step="1" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="虚拟销量" prop="virtualSalesCount">
              <el-input-number v-model="form.virtualSalesCount" :step="1" :min="0" step-strictly></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="封面图地址" prop="coverPicUrl">
              <imageUpload v-model="form.coverPicUrl" :limit="1"></imageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="轮播图地址" prop="bannerPicUrls">
              <imageUpload v-model="form.bannerPicUrls" :limit="100"></imageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item  label="视频地址" prop="bannerVideoUrls">
              <FileUpload :limit="100"  v-model="form.bannerVideoUrls" accept=".mp4,.mp3" :fileType="['mp4','mp3']" :fileModel="2" fileName="files" ></FileUpload>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :step="1" :min="0" step-strictly></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="租赁状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="item in dict.type.server_status"
                :key="item.value"
                :label="Number(item.value)">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="租赁简介" prop="introduction">
              <el-input type="textarea" v-model="form.introduction" :rows="6" placeholder="请输入关键字"/>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24" >
            <el-form-item label="租赁详情" prop="description">
              <editor v-model="form.description" :min-height="192"/>
            </el-form-item>
          </el-col> -->
          <el-col :span="24" >
            <el-form-item label="租赁详情" prop="description">
              <imageUpload v-model="form.description" :limit="100"></imageUpload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="popLodding" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as api from "@/api/commodity/leaseSpu";
import { rentCategoryAllList } from "@/api/commodity/leaseClass";
import { listAllOperator } from "@/api/operator/operatorList";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
name: "LeaseSpu",
dicts: ['server_status',],
components: { Treeselect, },
data() {
  return {
    popLodding:false,//弹窗加载
    form:{},
    // 弹出层标题
    title: "",
    // 是否显示弹出层
    open: false,
    // 遮罩层
    loading: true,
    // 显示搜索条件
    showSearch: true,
    queryParams: {// 查询参数
      pageNum: 1,name:null,categoryId:null,
      pageSize: 10,status:null,specType:null,operatorUserId:null,
    },
    // 总条数
    total: 0,
    rules: {
      operatorUserId: [{required: true, message: "运营商不能为空", trigger: "change"}],
      name: [{required: true, message: "租赁名称不能为空", trigger: "blur"}],
      keyword: [{required: true, message: "关键字不能为空", trigger: "blur"}],
      introduction: [{required: true, message: "租赁简介不能为空", trigger: "blur"}],
      description: [{required: true, message: "租赁详情不能为空", trigger: "blur"}],
      categoryId: [{required: true, message: "租赁分类不能为空", trigger: "change"}],
      coverPicUrl: [{required: true, message: "封面图地址不能为空", trigger: "change"}],
      bannerPicUrls: [{required: true, message: "轮播图地址不能为空", trigger: "change"}],
      sort: [{required: true, message: "排序字段不能为空", trigger: "blur"}],
      status: [{required: true, message: "租赁状态不能为空", trigger: "change"}],
      rent: [{required: true, message: "租金不能为空", trigger: "blur"}],
      deposit: [{required: true, message: "押金不能为空", trigger: "blur"}],
      virtualSalesCount: [{required: true, message: "虚拟销量不能为空", trigger: "blur"}],
    },
    list:[],//页面数据
    operatorList:[],//运营商数据
    categoryList:[],//分类数据
    xgztPermissions:'trade:rentSpu:updateStatus',//修改状态权限
    upDateStatusFlag:false,
  };
},
created() {
  const user = this.$store.state.user
  const permissions = user.permissions
  const flag = !!permissions.find(item => item == this.xgztPermissions)
  if( flag || permissions[0] == '*:*:*' ) this.upDateStatusFlag = true
  this.rentCategoryAllList()
  this.listAllOperator()
  this.getList()
},
methods: {
  // 状态修改
  handleStatusChange(row) {
    let text = row.status === 1 ? "上架" : "下架";
    this.$modal.confirm(`确认要${text}该数据吗？`).then(function() {
      return api.updateStatus({status:row.status,id:row.id,});
    }).then(() => {
      this.$modal.msgSuccess(text + "成功");
      this.getList()
    }).catch(()=> {
      row.status = row.status === 1 ? 0 : 1;
    });
  },
  getTypeStatus(value,index,index1){//禁用选项
    let properties = this.form.skus[index].properties || []
    return properties.find((item,indexs)=>item.propertyId == value && indexs != index1 ) ? true : false
  },
  async rentCategoryAllList(){//查询分类树列表
    let res = await rentCategoryAllList()
    let data = res.data || []
    this.categoryList = data
    this.findChild(this.categoryList)
  },
  findChild(list){//找到是否存在
    list.forEach(item=>{
      item.label = item.name
      let children = item.children || []
      if(children.length){
        this.findChild(children)
      }else{
        delete item.children
      }
    })
  },
  async listAllOperator(){//获取运营商
    let res =await listAllOperator()
    let data = res.data || []
    this.operatorList = data
  },
  getList() {
    this.loading = true;
    api.listRentSpu(this.queryParams).then(response => {
      let rows = response.rows || [];
      this.list = rows.map(item=>{
        return{...item,...this.getpricezh(item),}
      })
      this.total = response.total || 0;
      this.loading = false;
    });
  },
  handleAdd() {
    this.open = true;
    this.reset();
    this.title = "添加租赁spu";
  },
  handleUpdate(row) {
    this.reset();
    const id = row.id || this.ids;
    this.open = true;
    this.title = "修改租赁spu";
    api.getRentSpu(id).then(response => {
      let data = response.data || {}
      this.form = {
        ...data,...this.getpricezh(data),
      };
    });
  },
  getpricezh(item){//字段转换
    return {
      rent:this.math.divide(item.rent || 0,100),
      deposit:this.math.divide(item.deposit || 0,100),
    }
  },
  submitForm() {
    this.$refs["formRef"].validate(valid => {
      if (valid) {
        let form = {...this.form}
        this.popLodding = true
        if(this.getoperatorfunc(this).operatorUserId) delete form.operatorUserId
        form.rent = this.math.multiply(form.rent || 0,100)
        form.deposit = this.math.multiply(form.deposit || 0,100)
        if (this.form.id != undefined) {
          api.updateRentSpu(form).then(response => {
            this.popLodding = false
            this.$modal.msgSuccess("修改成功")
            this.open = false;
            this.getList();
          }).catch(error=>this.popLodding = false);
        } else {
          api.addRentSpu(form).then(response => {
            this.popLodding = false
            this.$modal.msgSuccess("新增成功")
            this.open = false;
            this.getList()
          }).catch(error=>this.popLodding = false);
        }
      }
    });
  },
  // 表单重置
  reset() {
    this.form = {
      status:1,
      operatorUserId:this.getoperatorfunc(this).operatorUserId,
    };
    this.resetForm("formRef");
    this.rentCategoryAllList()
    this.listAllOperator()
  },
  /** 搜索按钮操作 */
  handleQuery() {
    this.queryParams.pageNum = 1;
    this.getList();
  },
  /** 重置按钮操作 */
  resetQuery() {
    this.resetForm("queryForm");
    this.handleQuery();
  },
  handleDelete(row) {//删除
    const del_ids = row.id || this.ids;
    this.$modal.confirm('是否确认删除该数据项？').then(function() {
      return api.delRentSpu(del_ids);
    }).then(() => {
      this.getList();
      this.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  },
}
};
</script>
